<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="客户编码">
                        <el-input placeholder="请输入内容" v-model="params.customerCode" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="7">
                    <el-form-item label="客户简称">
                        <el-input placeholder="请输入内容" v-model="params.customerAbbreviation" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-form-item label="客户名称">
                        <el-input placeholder="请输入内容" v-model="params.customerName" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="状态">
                        <el-select v-model="params.status" placeholder="请选择" clearable :style="{ width: '100%' }">
                            <el-option label="是" value="0"></el-option>
                            <el-option label="否" value="1"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>
        </el-form>

        <el-button style="background-color:#ADD8E6 " @click="Insert" :icon="Plus">新增</el-button>
        <el-button style=" background-color: #90EE90" @click="updateID" :disabled="isSingleRowSelected"
            :icon="Edit">修改</el-button>
        <el-button style="background-color: #FFCCCB" plain :disabled="deleteDisabled" @click="Delete1"
            :icon="Delete">删除</el-button>

        <div style="display: flex; flex-direction: column; gap: 10px;">
            <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="customerCode" label="客户编码" width="150"></el-table-column>
                <el-table-column prop="customerName" label="客户名称" width="150"></el-table-column>
                <el-table-column prop="customerAbbreviation" label="客户简称" width="150"></el-table-column>
                <el-table-column prop="customerPhone" label="客户电话" width="150"></el-table-column>
                <el-table-column prop="customerType" label="客户类型" width="150" v-slot="options">
                    <!-- 使用 el-tag 以便于更好地显示客户类型 -->
                    <el-tag v-if="options.row.customerType == '0'" type="info">个人</el-tag>
                    <el-tag v-if="options.row.customerType == '1'" type="primary">私企</el-tag>
                </el-table-column>

                <el-table-column prop="status" label="是否启用" width="180" v-slot="options">
                    <el-tag :type="options.row.status == '0' ? 'success' : 'danger'">
                        {{ options.row.status == '0' ? '是' : '否' }}
                    </el-tag>
                </el-table-column>
                <el-table-column label="操作" width="300px">
                    <template #default="scope">
                        <el-button type="primary" link @click="Update(scope.row)" :icon="Edit">修改</el-button>
                        <el-button type="primary" link @click="Delete2(scope.row)" :icon="Delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row>
                <el-col :span="24">
                    <div class="demo-pagination-block">
                        <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                            :default-page-size="params.pageSize" :page-sizes="pageSizes"
                            layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </el-col>
            </el-row>



        </div>

        <!-- 弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="70%" @close="handleClose">
            <el-form :model="formData" ref="form" label-width="80px" :inline="false">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="客户编码">
                            <el-input v-model="formData.customerCode" placeholder="请输入客户编码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户名称">
                            <el-input v-model="formData.customerName" placeholder="请输入客户名称" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="客户英文名" label-width="100px">
                            <el-input v-model="formData.customerEnglishName" placeholder="请输入客户英文名称"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户简称">
                            <el-input v-model="formData.customerAbbreviation" placeholder="请输入客户简称"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="客户电话">
                            <el-input v-model="formData.customerPhone" placeholder="请输入客户电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">

                        <el-form-item label="客户类型">
                            <el-select v-model="formData.customerType" placeholder="请选择客户类型" clearable>
                                <el-option label="个人" value="0"></el-option>
                                <el-option label="私企" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="客户简介">
                            <el-input type="textarea" v-model="formData.customerArofile"
                                placeholder="请输入客户简介"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="客户地址">
                            <el-input type="textarea" v-model="formData.customerAddress"
                                placeholder="请输入客户地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="官方地址">
                            <el-input v-model="formData.officialAddress" placeholder="请输入客户官方地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="启用状态" label-width="100px">
                            <el-radio-group v-model="formData.status">
                                <el-radio value="0">是</el-radio>
                                <el-radio value="1">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱地址">
                            <el-input v-model="formData.emailAddress" placeholder="请输入客户邮箱地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="formData.remark" :autosize="{ minRows: 2, maxRows: 4 }"
                                placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button type="primary" @click="close">关闭</el-button>
                </el-form-item>
            </el-form>




        </el-dialog>



    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { deleteCustomer, findCustomer, insertCustomer, updateCustomer } from '@/apis/xms/index';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete, Plus, Edit } from '@element-plus/icons-vue';


let title = ref("");
let visible = ref(false);
const pageResult = ref({ total: 0 }); // 初始值包含 total 属性
let salesorder = ref([]); // 表格数据
const formData = ref({
    customerCode: '',
    customerName: '',
    customerEnglishName: '',
    customerAbbreviation: '',
    customerPhone: '',
    customerType: '',
    customerArofile: '',
    customerAddress: '',
    officialAddress: '',
    emailAddress: '',
    remark: '',
    status: '0'
});
// 弹窗表单数据

let ids = ref([]) // 选中行的id数组

const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行





// 分页大小
const pageSizes = [2, 5, 8, 10];

const params = ref({
    currentPage: 1,
    pageSize: 5,
    customerCode: '',
    customerAbbreviation: '',
    customerName: '',
    customerEnglishName: '',
    status: ''
});

// 搜索条件
const handleSearch = async () => {
    pageResult.value = await findCustomer(params.value)
    salesorder.value = pageResult.value.records
}
//处理分页大小
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await findCustomer(params.value)
    salesorder.value = pageResult.value.records
}

//处理当前分页数据
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await findCustomer(params.value)
    salesorder.value = pageResult.value.records
}

//查询数据
onMounted(async () => {
    pageResult.value = await findCustomer(params.value)
    console.log(pageResult.value)
    salesorder.value = pageResult.value.records
})


/**
 * 新增单位弹窗显示层
 * @param index 
 * @param row 
 */
const Insert = () => {
    visible.value = true;
    title.value = "新增客户";
}



/**
 * 修改单位弹窗显示层
 * @param index 
 * @param row 
 */
const Update = (row) => {
    console.log(row)
    visible.value = true;
    title.value = "修改客户";
    formData.value = { ...row }; // 直接使用 row 的数据  
}


const updateID = () => {
    visible.value = true;
    title.value = "修改客户";
}

/**
 * 添加修改表单数据提交
 */
const onSubmit = async () => {
    if (title.value == "新增客户") {
        await insertCustomer(formData.value)
    } else {
        await updateCustomer(formData.value)
    }
    visible.value = false
    ElMessage.success(`${title.value}成功`)
    handleSearch();

}



const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.customerId) // 使用map方法过滤出选中行的logId数组

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formData.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }
}



//批量删除
const Delete1 = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteCustomer(ids.value);  // 将单个ID传递给 deleteCustomer 
        console.log(`删除的ID:`, ids.value);
        pageResult.value = await findCustomer(params.value);
        salesorder.value = pageResult.value.records;
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};



//行内删除
const Delete2 = async (row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${row.customerId}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteCustomer([row.customerId]);  // 将单个ID传递给 deletesspplier 方法

        console.log(`删除的ID:`, row.customerId);

        // 从表格数据中移除当前行
        salesorder.value = salesorder.value.filter(item => item.customerId !== row.customerId);

        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};




/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}


/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    resetData()
}
/**
 * 重置数据
 */
function resetData() {
    formData.value = {}
    title.value = ''
}



let close = () => {
    visible.value = false;
    loadData();
};

/**
 * 加载数据
 */
const loadData = async () => {
    await handleSearch();
};

/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        materialName: '',
        status: null
    }
    handleSearch();
}
</script>



<style scoped>
.demo-pagination-block {
    display: flex;
    /* 使其成为 flexbox 容器 */
    justify-content: flex-end;
    /* 将内容对齐到右侧 */
    margin-top: 20px;
}
</style>